package com.pn.controller;

import com.pn.entity.SysMenu;
import com.pn.service.SysMenuService;
import com.pn.vo.AuthMenuVo;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@RequestMapping("/sys/menu")
@RestController
public class SysMenuController {

    //注入SysMenuService
    @Autowired
    private SysMenuService menuService;

    /**
      加载用户权限菜单树的url接口/sys/menu/nav:

      请求处理方法的返回值ResponseEntity对象：
       后台向前台做响应其实就是向前台发送响应协议，而响应协议包含响应状态码 响应头 响应体;而ResponseEntity
       响应实体对象就代表整个响应协议,它就包含了响应状态码 响应头 响应体;所以我们的所有请求处理方法的返回值就
       是ResponseEntity响应实体对象即就是向前端做响应;ResponseEntity响应实体对象的泛型是响应正文的类型;
     */
    @RequestMapping("/nav")
    public ResponseEntity<AuthMenuVo> loadMenuTree(){

        //执行业务查询用户权限菜单树
        List<SysMenu> menuTreeList = menuService.menuTreeByUid();

        //拿用户的所有权限
        Collection<? extends GrantedAuthority> grantedAuthorityList =
                SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        List<String> authorities = new ArrayList<>();
        for (GrantedAuthority grantedAuthority : grantedAuthorityList) {
            authorities.add(grantedAuthority.getAuthority());
        }

        //创建Vo对象并封装用户权限菜单树和用户的所有权限
        AuthMenuVo authMenuVo = new AuthMenuVo(menuTreeList, authorities);

        /*
          响应:
          ResponseEntity.ok()表示成功响应,如果有响应正文则将响应正文作为参数传递给ok()方法,如果没有响应
          正文ok()方法不用传参且连调build();
         */
        return ResponseEntity.ok(authMenuVo);

    }
}
